#!/bin/bash
#

# ----------------------------------------------------------
# base setup

ARCH=x86_64
PRODUCT="anbox_${ARCH}"
VARIANT="userdebug"

#----------------------------------------------------------
# local functions

TMPDIR=/tmp
GETOPT=getopt
CP="cp -rvf"

if [[ "$OSTYPE" == "linux-gnu" ]]; then
  NR_CPU=$(grep processor /proc/cpuinfo | awk '{field=$NF};END{print field+1}')
elif [[ "$OSTYPE" == "darwin"* ]]; then
  GETOPT=ggetopt
  CP="cp -Rvf"
  NR_CPU=4
  NO_LINUX=true
fi

MAKE="make -j${NR_CPU}"

function run_cmd() {
  [ "$V" = "1" ] && echo "+ ${@}"
  eval $@ || exit $?
}

function usage() {
  echo "Usage: $0 [ARGS]"
  echo
  echo "Options:"
  echo "  -a         build Android target"
  echo "  -m ARCH    set target arch x86_64(default) or arm64"
  echo
  echo "  -M         make Anbox image"
  echo "  -h         show this help message and exit"
  exit 1
}

function parse_args() {
  [ -z "$1" ] && usage;
  TEMP=`$GETOPT -o "am:FMh" --long "all" -n "$SELF" -- "$@"`
  if [ $? != 0 ] ; then exit 1; fi
  eval set -- "$TEMP"

  while true; do
    case "$1" in
      -a ) BUILD_ANDROID=true;    shift 1;;
      -m ) ARCH=$2;               shift 2;;
      -M ) MAKE_ANBOX_IMG=true;   shift 1;;
      -F|--all)
	 BUILD_ANDROID=true; MAKE_ANBOX_IMG=true; shift 1;;
      -h ) usage; exit 1 ;;
      -- ) shift; break  ;;
      *  ) echo "invalid option $1"; usage; return 1 ;;
    esac
  done
}

function build_android() {
  source build/envsetup.sh >/dev/null
  run_cmd lunch ${PRODUCT}-${VARIANT}
  run_cmd ${MAKE} $*
}

function make_image() {
  if [ -z ${TARGET_PRODUCT} ]; then
    source build/envsetup.sh >/dev/null
    run_cmd lunch ${PRODUCT}-${VARIANT}
  fi

  if [ -z ${NO_LINUX} ]; then
    cd ./vendor/anbox
    run_cmd sudo ./scripts/create-package.sh   \
            ${ANDROID_PRODUCT_OUT}/ramdisk.img \
            ${ANDROID_PRODUCT_OUT}/system.img
    mv -fv android.img ../../android_${TARGET_PRODUCT}.img
  else
    echo ""
    echo "--- please run in linux ---"
    echo ""
  fi
}

#----------------------------------------------------------

parse_args $@

case $ARCH in
  x86_64)        ARCH=x86_64;;
  aarch64|arm64) ARCH=arm64;;
  *)
    echo "Invalid arch '$ARG', please use x86_64 or arm64"
    exit -1
  ;;
esac

PRODUCT="anbox_${ARCH}"
VARIANT=${VARIANT:-"userdebug"}

[ "$BUILD_ANDROID"  = true ] && build_android
[ "$MAKE_ANBOX_IMG" = true ] && make_image
